package com.jinzhi.jzweb.controller.moduleConfig;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.ExaminationBatchComDO;
import com.jinzhi.jzweb.domain.moduleConfig.CareStuSignUpComRealityDO;
import com.jinzhi.jzweb.domain.moduleConfig.EncipherDO;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.pojo.moduleConfig.CareStuSignUpComRealityChildrenDownloadVo;
import com.jinzhi.jzweb.pojo.moduleConfig.CareStuSignUpComRealityDownloadVo;
import com.jinzhi.jzweb.pojo.moduleConfig.CareStuSignUpComRealityVo;
import com.jinzhi.jzweb.service.ExaminationAnswerSheetComService;
import com.jinzhi.jzweb.service.ExaminationBatchComService;
import com.jinzhi.jzweb.service.ExaminationResultsComService;
import com.jinzhi.jzweb.service.moduleConfig.CareStuSignUpComRealityService;
import com.jinzhi.jzweb.service.moduleConfig.EncipherService;
import com.jinzhi.jzweb.strategy.factory.PayStrategyFactory;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.SysUserRelevancyService;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 选手管理 实操
 * </pre>
 * <small> 2023-05-05 08:52:02 | lance</small>downloadImportStu
 */
@Controller
@RequestMapping("/jzweb/shicaoSignUpComReality")
@Api(value = "用户需求后台管理", tags = "用户需求后台管理")
public class ShiCaoSignUpComRealityController extends BaseController {


	private final PayStrategyFactory payStrategyFactory;

	private final CareStuSignUpComRealityService careStuSignUpComRealityService;

	private final UserService userService;

	private final ExaminationBatchComService examinationBatchService;

	private final ExaminationAnswerSheetComService examinationAnswerSheetService;

	private final SysUserRelevancyService userRelevancyService;

	private final ExaminationResultsComService examinationResultsComService;

	private final EncipherService encipherService;

	public ShiCaoSignUpComRealityController(PayStrategyFactory payStrategyFactory, CareStuSignUpComRealityService careStuSignUpComRealityService, UserService userService, ExaminationBatchComService examinationBatchService, ExaminationAnswerSheetComService examinationAnswerSheetService, SysUserRelevancyService userRelevancyService, ExaminationResultsComService examinationResultsComService,EncipherService encipherService) {
		this.payStrategyFactory = payStrategyFactory;
		this.careStuSignUpComRealityService = careStuSignUpComRealityService;
		this.userService = userService;
		this.examinationBatchService = examinationBatchService;
		this.examinationAnswerSheetService = examinationAnswerSheetService;
		this.userRelevancyService = userRelevancyService;
		this.examinationResultsComService = examinationResultsComService;
		this.encipherService = encipherService;
	}




	@GetMapping()
	@RequiresPermissions("jzweb:shicaoSignUpComReality:shicaoSignUpComReality")
	String StuSignUpCom(Integer types,Model model){
		model.addAttribute("types",types);
	    return "jzweb/shicaoSignUpComReality/shicaoSignUpComReality";
	}


		/**
         * 第一次加密选手导出信息
         *
         * @param response
         */
	@GetMapping("/downloadImportStu")
	@RequiresPermissions("jzweb:shicaoSignUpComReality:import")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response, CareStuSignUpComRealityDO stuSignUpComDTO) {
		List<CareStuSignUpComRealityDownloadVo> list1 = new LinkedList<>();
		Wrapper<CareStuSignUpComRealityDO> wrapper = new EntityWrapper<CareStuSignUpComRealityDO>().orderBy("com_nums", true);

		if(StringUtils.isNotBlank(stuSignUpComDTO.getName())){
			wrapper.like("name",stuSignUpComDTO.getName());
		}
		if(stuSignUpComDTO.getCbatchName()!=null){
			ExaminationBatchComDO examinationBatchComDO1=	examinationBatchService.findOneByKv("name",stuSignUpComDTO.getCbatchName());

			wrapper.like("cbatch_id",examinationBatchComDO1.getId().toString());
		}
		List<CareStuSignUpComRealityDO> list=careStuSignUpComRealityService.selectList(wrapper);
		if(list!=null && !list.isEmpty()){
			Map<String, List<CareStuSignUpComRealityDO>> groupedRecords = list.stream()
					.collect(Collectors.groupingBy(CareStuSignUpComRealityDO::getUnitName));
			for (Map.Entry<String, List<CareStuSignUpComRealityDO>> entry : groupedRecords.entrySet()) {
				if(entry.getValue().size()==2){
					CareStuSignUpComRealityDownloadVo careStuSignUpComRealityDownloadVo = new CareStuSignUpComRealityDownloadVo();
					List<CareStuSignUpComRealityChildrenDownloadVo> childrenLists = new LinkedList<>();
					BeanUtils.copyProperties(entry.getValue().get(0),careStuSignUpComRealityDownloadVo);
					CareStuSignUpComRealityChildrenDownloadVo careStuSignUpComRealityChildrenDownloadVo1 = new CareStuSignUpComRealityChildrenDownloadVo();
					CareStuSignUpComRealityChildrenDownloadVo careStuSignUpComRealityChildrenDownloadVo2 = new CareStuSignUpComRealityChildrenDownloadVo();
					BeanUtils.copyProperties(entry.getValue().get(0),careStuSignUpComRealityChildrenDownloadVo1);
					BeanUtils.copyProperties(entry.getValue().get(1),careStuSignUpComRealityChildrenDownloadVo2);
					childrenLists.add(careStuSignUpComRealityChildrenDownloadVo1);
					childrenLists.add(careStuSignUpComRealityChildrenDownloadVo2);
					careStuSignUpComRealityDownloadVo.setChildrenList(childrenLists);
					list1.add(careStuSignUpComRealityDownloadVo);
				}
			}
		}
		//导出操作
		EasyPoiUtil.exportExcel(list1, "考生报名信息导出", "考生报名信息导出", CareStuSignUpComRealityDownloadVo.class, "考生报名信息导出", response);
	}


	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:shicaoSignUpComReality:shicaoSignUpComReality")
	public Result<Page<CareStuSignUpComRealityDO>> list(CareStuSignUpComRealityDO stuSignUpComDTO){

		Wrapper<CareStuSignUpComRealityDO> wrapper=new EntityWrapper<>();

		if(StringUtils.isNotBlank(stuSignUpComDTO.getName())){
			wrapper.like("name",stuSignUpComDTO.getName());
		}
		if(StringUtils.isNotBlank(stuSignUpComDTO.getCbatchName())){
			ExaminationBatchComDO examinationBatchComDO1=	examinationBatchService.findOneByKv("name",stuSignUpComDTO.getCbatchName());
			if(examinationBatchComDO1!=null){
				wrapper.like("cbatch_id",examinationBatchComDO1.getId().toString());
			}

		}
		// 查询列表数据
		Page<CareStuSignUpComRealityDO> page = careStuSignUpComRealityService.selectPage(getPage(CareStuSignUpComRealityDO.class),wrapper);

		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
				CareStuSignUpComRealityDO obj = (CareStuSignUpComRealityDO) page.getRecords().get(i);
			ExaminationBatchComDO examinationBatchComDO=examinationBatchService.selectById(obj.getCbatchId());
			if(examinationBatchComDO!=null){
				obj.setCbatchName(examinationBatchComDO.getName());
			}
			obj.setProvince(obj.getProvince()+","+obj.getCity());
			Wrapper<EncipherDO> doWrapper = new EntityWrapper<EncipherDO>().eq("stu_id", page.getRecords().get(i).getId()).eq("field", "3");
			List<EncipherDO> encipherDOS = encipherService.selectList(doWrapper);
			if(null!=encipherDOS && !encipherDOS.isEmpty()){
				page.getRecords().get(i).setNum1(encipherDOS.get(0).getNum1()!=null?encipherDOS.get(0).getNum1():null);
				page.getRecords().get(i).setNum2(encipherDOS.get(0).getNum2()!=null?encipherDOS.get(0).getNum2():null);
			}else{
				page.getRecords().get(i).setNum1(null);
				page.getRecords().get(i).setNum2(null);
			}

			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:shicaoSignUpComReality:add")
	String add(){

	    return "jzweb/shicaoSignUpComReality/add";
	}


	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:shicaoSignUpComReality:edit")
	String edit(@PathVariable("id") Long id,Model model){
		CareStuSignUpComRealityDO stuSignUpCom = careStuSignUpComRealityService.selectById(id);
		encipherService.delete(new EntityWrapper<EncipherDO>().eq("stu_id",id).eq("field","3"));
		model.addAttribute("stuSignUpCom", stuSignUpCom);
		return "jzweb/shicaoSignUpComReality/edit";
	}


	@Log("添加考生报名")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:shicaoSignUpComReality:add")
	@Transactional
	public Result<String> save( CareStuSignUpComRealityDO stuSignUpCom){
		Integer maxNum=careStuSignUpComRealityService.MaxNum(stuSignUpCom.getCbatchId());
		ExaminationBatchComDO examinationBatchComDO=examinationBatchService.selectById(stuSignUpCom.getCbatchId());
		if(examinationBatchComDO==null){
			return Result.fail("出现了错误，考试批次不存在！");
		}
		if(StringUtils.isBlank(examinationBatchComDO.getCompetitionName())){
			return Result.fail("未录入竞赛编号无法进行录入！");
		}
		stuSignUpCom.setState(3);
		if(stuSignUpCom.getTypes()==3){
			stuSignUpCom.setCourt("A");
		}
		if(maxNum==null){
			maxNum=0;
		}
		Integer nums=maxNum+1;
		String comName=examinationBatchComDO.getCompetitionName()+"00"+nums;
		stuSignUpCom.setComNum(nums);
		stuSignUpCom.setComNums(comName);
		stuSignUpCom.setCompetitionType(3);

		stuSignUpCom.setSignUpTime(new Date());
		careStuSignUpComRealityService.insert(stuSignUpCom);
		return Result.ok();
	}


	@Log("修改考生报名")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:shicaoSignUpComReality:edit")
	@Transactional
	public Result<String>  update( CareStuSignUpComRealityDO stuSignUpCom){

		CareStuSignUpComRealityDO stuSignUpComDO1=	careStuSignUpComRealityService.selectById(stuSignUpCom.getId());

//		List<CareStuSignUpComRealityDO> list =	stuSignUpComService.findByKv("num2",stuSignUpCom.getNum1(),
//				"court",stuSignUpCom.getCourt(),"cbatch_id",stuSignUpComDO1.getCbatchId());

		Wrapper<CareStuSignUpComRealityDO> wrapper=new EntityWrapper<>();
		wrapper.eq("court",stuSignUpComDO1.getCourt());
		wrapper.eq("cbatch_id",stuSignUpComDO1.getCbatchId());
		wrapper.eq("num2",stuSignUpCom.getNum2());
		List<CareStuSignUpComRealityDO> list =	careStuSignUpComRealityService.selectList(wrapper);
		if(list.size()>0){
			for(CareStuSignUpComRealityDO li:list){
				if(!li.getId().equals(stuSignUpCom.getId())){
					return  Result.fail("加密序号重复！");
				}
			}

		}

		boolean update = careStuSignUpComRealityService.updateById(stuSignUpCom);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除考生报名")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:shicaoSignUpComReality:remove")
	public Result<String>  remove( Long id){
		careStuSignUpComRealityService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除考生报名")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:shicaoSignUpComReality:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		careStuSignUpComRealityService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}


	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importComError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:shicaoSignUpComReality:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考生报名导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("stuSignComUp" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}


	/**
	 * 导如模板 信息
	 * @throws Exception
	 */
	@GetMapping("/exportList")
	@ResponseBody
	public void exportlist( HttpServletRequest request, HttpServletResponse responseexa) throws Exception{

		List<CareStuSignUpComRealityVo> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "实际选手导入模板", "实际选手导入模板", CareStuSignUpComRealityVo.class, "实际选手导入模板", responseexa);

	}


	/**
	 * 考生信息导入
	 *
	 * @param file excel文件
	 */
	@Log("考生信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:shicaoSignUpComReality:import")
	public Result<?> importExcel(HttpServletRequest req, @RequestParam("file") MultipartFile file, String cbatchId,Integer type) {
		//---------------------------------检测导入信息及条件-----------------------------------------
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<CareStuSignUpComRealityVo> list = EasyPoiUtil.importExcel(file, 1, 1, CareStuSignUpComRealityVo.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}


		//第四步--判断该认证批次是否已经建立了理论考试批次；
		//todo 目前定义为只要是认证批次，就一定存在理论考试
		List<ExaminationBatchComDO> examinationBatchDO = examinationBatchService.findByKv("id", Long.parseLong(cbatchId), "type", 0);

		//---------------------------------验证数据并导入-----------------------------------------
		//数据该市行为第三行，第一行标题，第二行表头
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<CareStuSignUpComRealityDO> upDOList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			UserDO rrUserDo = null;
			UserDO rsUserDo = null;
			StringBuilder sb = new StringBuilder();
			//第一步验证是否存在空值
			if (StringUtils.isBlank(list.get(i).getUnitName())) {
				sb.append("第" + (i + startRow) + "行参赛单位未填写，请完善！" + ";");
			} else {
				if (StringUtils.isBlank(list.get(i).getTeamLeader())) {
					sb.append("第" + (i + startRow) + "行领队未填写，请完善！" + ";");
				} else {
					if (StringUtils.isBlank(list.get(i).getTeacher())) {
						sb.append("第" + (i + startRow) + "行指导老师未填写，请完善！" + ";");
					}else {
						if (StringUtils.isBlank(list.get(i).getName())) {
							sb.append("第" + (i + startRow) + "行选手姓名未填写，请完善！" + ";");
						} else {
							if (StringUtils.isBlank(list.get(i).getSex())) {
								sb.append("第" + (i + startRow) + "行性别未填写，请完善！" + ";");
							} else {
								if (StringUtils.isBlank(list.get(i).getNation())) {
									sb.append("第" + (i + startRow) + "行民族未填写，请完善！" + ";");
								} else {
									if (StringUtils.isBlank(list.get(i).getIdNumber())) {
										sb.append("第" + (i + startRow) + "行身份证号码未填写，请完善！" + ";");
									} else {
										if (StringUtils.isBlank(list.get(i).getTicketNumber())) {
											sb.append("第" + (i + startRow) + "行联系方式未填写，请完善！" + ";");
										} else {

										}
									}
								}
							}
						}

						if (sb.length() == 0) {
							//第四步排重验证（自身比较）
//								for (int j = 0; j < list.size(); j++) {
//									if (i != j) {
//										if (list.get(i).getTicketNumber().equals(list.get(j).getTicketNumber())) {
//											sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行准考证号重复，重复值：" + list.get(i).getIdNumber() + ";");
//										}
//									}
//								}

							//第六步排重验证（和数据库比较），根据考生名称、考生身份证号码、该场考试的认证批次判断该考生是否已报名该考试
							CareStuSignUpComRealityDO stuSignUpDO = careStuSignUpComRealityService.findOneByKv("name", list.get(i).getName(), "id_number", list.get(i).getIdNumber(), "cbatch_id", Long.parseLong(cbatchId));
							if (stuSignUpDO != null) {
								sb.append("第" + (i + startRow) + "行考生已报名该次考试！" + ";");
							}

						}

					}
				}

			}

			if (sb.length() > 0) {
				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setSeq(cout);
				cout += 1;
				errorCodeVo.setErrorCode(sb.toString());
				list1.add(errorCodeVo);
			} else {
				if (rrUserDo != null) {
					boolean cc = userService.insertNoPW(rrUserDo);
					if (!cc) {
					}
				}
			}

			CareStuSignUpComRealityDO stuSignUpDO1 = new CareStuSignUpComRealityDO();
			BeanUtils.copyProperties(list.get(i),stuSignUpDO1);
			stuSignUpDO1.setName(list.get(i).getName());//姓名
			stuSignUpDO1.setIdNumber(list.get(i).getIdNumber());//身份证号码
			stuSignUpDO1.setCbatchId(Long.parseLong(cbatchId));//认证批次id
			stuSignUpDO1.setSignUpTime(new Date());//报名时间
			stuSignUpDO1.setDecrypt(0);
			stuSignUpDO1.setCompetitionType(3);
			stuSignUpDO1.setType(0);
			stuSignUpDO1.setState(3);//默认已分配
			stuSignUpDO1.setTypes(type);
			stuSignUpDO1.setCourt("A");
			stuSignUpDO1.setTeamLeader(list.get(i).getTeamLeader());
			stuSignUpDO1.setUnitName(list.get(i).getUnitName());

				stuSignUpDO1.setTicketNumber(list.get(i).getTicketNumber());//考号

				stuSignUpDO1.setCheckerId(this.getUserId());//默认审核人为导入者
				stuSignUpDO1.setCheckerDate(new Date());//默认审核时间为导入时间
				upDOList.add(stuSignUpDO1);

			}
		Integer maxNum=careStuSignUpComRealityService.MaxNum(Long.valueOf(cbatchId));
		if(maxNum==null){
			maxNum=0;
		}
		ExaminationBatchComDO examinationBatchComDO=examinationBatchService.selectById(Long.valueOf(cbatchId));
		if(examinationBatchComDO==null){
			return Result.fail("出现了错误，考试批次不存在！");
		}
		if(StringUtils.isBlank(examinationBatchComDO.getCompetitionName())){
			return Result.fail("未录入竞赛编号无法进行录入！");
		}
		Integer nums=maxNum+1;
		//赋值竞赛编号
		for(CareStuSignUpComRealityDO li:upDOList){

			String comName=examinationBatchComDO.getCompetitionName()+"00"+nums;
			li.setComNum(nums);
			li.setComNums(comName);
			nums++;
		}

		if (list1.size() == 0) {
			boolean c = careStuSignUpComRealityService.insertBatch(upDOList, upDOList.size());
			if (c) {
				ExaminationBatchComDO examinationBatchDOs = examinationBatchService.findOneByKv("cbatch_id", Long.parseLong(cbatchId), "type", 1);


				return Result.ok("成功导入" + list.size() + "条数据");
			} else {

				return Result.fail("报名信息导入错误，请稍后重试或联系管理员");
			}
		} else {


			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("stuSignComUp" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
	}

}
